package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.LockUtil;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private SeckillVoucherServiceImpl voucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;
    private final static DefaultRedisScript<Long> REDIS_SCRIPT;
    private static BlockingQueue<VoucherOrder> blockingQueue = new ArrayBlockingQueue<>(1024 * 1024);
    private static ExecutorService executorService = Executors.newFixedThreadPool(3);

    static {
        REDIS_SCRIPT = new DefaultRedisScript();
        REDIS_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        REDIS_SCRIPT.setResultType(Long.class);

    }
    private IVoucherOrderService proxy;
    private Runnable task = () -> {
        while (true) {
            RLock lock = null;
            try {
                VoucherOrder order = blockingQueue.take();
                 lock = redissonClient.getLock("lock:Order:" + order.getUserId());
                boolean success = lock.tryLock();
                if (!success) {
                     log.error("不允许重复下单");
                }
                 proxy.createVoucherOrder(order);
            } catch (Exception e) {
                log.error("订单处理异常");
            }
           finally {
                lock.unlock();
            }
        }
    };
    @PostConstruct
private void init(){
    executorService.submit(task);
}
    @Transactional
    public void createVoucherOrder(VoucherOrder order) {
        // 6.1.查询订单
        int count = query().eq("user_id", order.getUserId()).eq("voucher_id", order.getVoucherId()).count();
        // 6.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            log.error("用户已经购买过了");
            return ;
        }
        //7.减少库存
        boolean update = voucherService.update().setSql("stock = stock - 1").eq("voucher_id", order.getVoucherId()).gt("stock", 0).update();
        if (!update) {
            log.error("库存不足");
        }
        //8.保存订单
        save(order);
    }


    public Result seckillVoucher(Long voucherId) {
        //1.根据id查询秒杀券 select * from seckillvoucher where id = voucherId
        //注意这个实现类关联的表是订单表，我们得调用Voucher表的实现类
        SeckillVoucher sVoucher = voucherService.query().eq("voucher_id", voucherId).one();
        //2.判断秒杀是否开始
        if (LocalDateTime.now().isBefore(sVoucher.getBeginTime()) ||
                LocalDateTime.now().isAfter(sVoucher.getEndTime())) {
            //3.未开始，返回秒杀未开始
            return Result.fail("不在秒杀时间段哦!");
        }
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(REDIS_SCRIPT, Collections.emptyList(),
                voucherId.toString(), UserHolder.getUser().getId().toString()
        );
        int r = result.intValue();
        //2.判断result是否为0
        if (r != 0) {
            //2.1不是，返回异常信息
            return Result.fail(r == 1 ? "库存不足" : "重复下单");
        }
        //2.2 TODO 是，下单任务存入阻塞队列
        long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(sVoucher.getVoucherId());
        voucherOrder.setUserId(UserHolder.getUser().getId());
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        blockingQueue.offer(voucherOrder);
        return Result.ok(orderId);
    }
}

